import { useMount, useRequest } from 'ahooks';
import { Button, message } from 'antd';

import {
  editAttrValue,
  findByValueListByAttrId,
} from '@/services/sys/attribute';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { BetaSchemaForm, ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { undefined } from '@umijs/utils/compiled/zod';
import { useRef, useState } from 'react';
import { history } from 'umi';

const valueEnum = {
  empty: { text: '默认', status: '' },
  Default: { text: '待发布状态', status: 'Default' },
  Processing: { text: '发布中状态', status: 'Processing' },
  Success: { text: '发布成功状态', status: 'Success' },
  Error: { text: '发布失败状态', status: 'Error' },
};
const request = async () => {
  const valueEnum1 = [
    { label: '默认', value: 'empty' },
    { label: '待发布状态', value: 'Default' },
    { label: '发布中状态', value: 'Processing' },
    { label: '发布成功状态', value: 'Success' },
    { label: '发布失败状态', value: 'Error' },
  ];
  return valueEnum1;
};

const columnDialog = [
  {
    title: '基本信息',
    valueType: 'group',
    columns: [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'id',
        initialValue: 0,
        hideInForm: true,
      },
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        width: 'md',
      },
      {
        title: '关键字',
        dataIndex: 'isValue',
        width: 'md',
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 'md',
        request,
      },

      {
        title: '备注',
        dataIndex: 'remark',
        valueType: 'textarea',
        width: 'md',
      },
    ],
  },
];

const AttrValue = () => {
  // @ts-ignore
  const formRef = useRef<ProFormInstance>();
  const column = [
    {
      title: '编号',
      dataIndex: 'index',
      key: 'index',
      valueType: 'indexBorder',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 'md',
    },
    {
      title: '关键字',
      dataIndex: 'isValue',
      width: 'md',
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum,
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      width: '164px',
      key: 'option',
      valueType: 'option',
      render: (_: any, row: any, index: any) => [
        <a
          key="link"
          onClick={() => {
            console.log(row);

            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            editDialogInfo(row);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];
  const [editDialg, setEditDialg] = useState(false);
  const [attribute, setAttribute] = useState<API.Attribute>();
  const [attributeValue, setAttributeValue] = useState<API.AttributeValue>();
  const {
    run: fetchByValueListByAttrI,
    refresh,
    data: dataList,
    loading,
  } = useRequest(findByValueListByAttrId, {
    debounceWait: 100,
    manual: true,
  });

  function editDialogInfo(row: API.AttributeValue) {
    setAttributeValue(row);
    formRef?.current?.setFieldsValue(row);
    setEditDialg(true);
  }

  function hideEditDialg() {
    // @ts-ignore
    setAttributeValue({
      attributeId: 0,
      isValue: undefined,
      name: '',
      parentId: undefined,
      remark: '',
      status: '',
      id: 0,
    });
    formRef.current?.resetFields();
    setEditDialg(false);
  }

  function openEditDialg() {
    // @ts-ignore
    setAttributeValue({ id: 0 });
    formRef.current?.resetFields();
    setEditDialg(true);
  }

  useMount(async () => {
    // history 栈的实体个数
    console.log(history.location.state);

    // 当前 history 跳转的action, 有push/replace/pop 三种类型
    console.log(history.action);

    // location 对象，包含 pathname/search/hash
    console.log(history.location.pathname);
    console.log(history.location.search);
    console.log(history.location.hash);
    console.log(history.location.query);
    // @ts-ignore
    setAttribute(history.location.state);
    fetchByValueListByAttrI(history.location.state?.id);
  });

  return (
    <div>
      <BetaSchemaForm<API.AttributeValue>
        formRef={formRef}
        initialValues={attributeValue}
        onCancel={() => setEditDialg(false)}
        onVisibleChange={setEditDialg}
        title="字典管理"
        visible={editDialg}
        layoutType="ModalForm"
        columns={columnDialog}
        onFinish={async (values) => {
          values.id = attributeValue?.id;
          values.attributeId = attribute?.id;
          console.log(values);
          return new Promise<boolean>((resolve, reject) => {
            editAttrValue(values)
              .then(() => {
                message.success('操作成功');
                setEditDialg(false);
                refresh();
                resolve(true);
              })
              .catch(() => {
                message.success('操作失败');
                reject(false);
              });
          });
        }}
      />
      <ProTable<API.AttributeValue>
        search={false}
        toolBarRender={() => [
          <Button
            onClick={() => {
              formRef.current?.resetFields();
              openEditDialg();
            }}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            新建
          </Button>,
        ]}
        headerTitle={
          <PageContainer
            className="site-page-header"
            onBack={() => window.history.back()}
            title={attribute?.name}
            subTitle={attribute?.iskey}
          />
        }
        onDataSourceChange={(d) => {
          console.log('onDataSourceChange', d);
        }}
        onLoad={(d) => {
          // 数据加载完操作
          console.log('onDataSourceChange', d);
        }}
        dataSource={dataList}
        loading={loading}
        columns={column}
      ></ProTable>
    </div>
  );
};

export default AttrValue;
